package com.mayikt;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import com.spring4all.swagger.EnableSwagger2Doc;

import springfox.documentation.swagger.web.SwaggerResource;
import springfox.documentation.swagger.web.SwaggerResourcesProvider;

@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
@EnableSwagger2Doc
@EnableApolloConfig
@MapperScan("com.mayikt.zuul.mapper")
public class AppGateWay {

    public static void main(String[] args) {
        SpringApplication.run(AppGateWay.class, args);
    }
//    远程获取apollo config
//    注：也可以使用@value注解，使用注解是饿汉式加载，一启动就去加载配置文件
    @ApolloConfig
    private Config config;
    // 添加文档来源
    @Component
    @Primary
    class DocumentationConfig implements SwaggerResourcesProvider {
        @Override
        public List<SwaggerResource> get() {
            return resources();
        }

        private List<SwaggerResource> resources(){
            List resources = new ArrayList<>();
            String swaggerJson = swaggerDocument();
            JSONArray jsonArray = JSONArray.parseArray(swaggerJson);
            for (Object object : jsonArray) {
                JSONObject jsonObject = (JSONObject)object;
                resources.add(swaggerResource(jsonObject.getString("name")
                        ,jsonObject.getString("location")
                        ,jsonObject.getString("version")));
            }
            // app-itmayiedu-order
//            resources.add(swaggerResource("app-mayikt-member", "/app-mayikt-member/v2/api-docs", "2.0"));
//            resources.add(swaggerResource("app-mayikt-weixin", "/app-mayikt-weixin/v2/api-docs", "2.0"));
            return resources;
        }

        private SwaggerResource swaggerResource(String name, String location, String version) {
            SwaggerResource swaggerResource = new SwaggerResource();
            swaggerResource.setName(name);
            swaggerResource.setLocation(location);
            swaggerResource.setSwaggerVersion(version);
            return swaggerResource;
        }

//        远程获取阿波罗apollo服务器上的配置文件
        private String swaggerDocument(){
            String property = config.getProperty("myyikt.zuul.swagger.document", "");
            return property;
        }
    }

}
